Skip to main content

Class

  • 有三種 Access Modifiers 可以用:publicprivateprotected

    protected: 類似 private,但在子類別裡面可以被調用

  • 繼承用關鍵字 extends

  • readonly: 不能再被修改

  • 基本寫法

    class Animal {
    public readonly name: string
    constructor(name: string) {
    this.name = name
    }

    public SayHi() {
    console.log(`${this.name} say hi`)
    }
    }

    const animal = new Animal('test')
    console.log(animal)

    // readonly 不能被修改,會報錯
    animal.name = 'test2'
  • static 靜態屬性、方法

    不需要 instance,可以直接用 class 名稱呼叫

    class Animal {
    public name: string;
    public static order = 1;

    constructor(name: string) {
    this.name = name;
    }

    static SayHi() {
    console.log("Hi!");
    }
    }

    Animal.SayHi();
    console.log(Animal.order);
  • Abstract Class

    • 作為基底

    • 方法可以實現或寫成 abstract

    • 寫成 abstract 的好處是可以強迫 extends 的 class 都要實現方法

      abstract class Animal {
      // 子類別才可調用
      protected name: string

      constructor(name: string) {
      this.name = name
      }

      abstract sayHi(): void
      }

      class Dog extends Animal {
      // 如果建構子一樣,可以不寫
      constructor(name: string) {
      super(name)
      }

      // need to implement
      sayHi(): void {
      console.log(`${this.name} say hi!`)
      }
      }

      const dog: Dog = new Dog('Doggy')
      dog.sayHi()
  • Parameter Properties(精簡的寫法)

    把修飾詞寫在建構子裡面

    class Student {
    constructor(public name: string, private age: number) {}
    }

    const student = new Student('Sam', 27)

    console.log(student.name)

    等同此寫法

    class Student {
    name: string;
    age: number;
    constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
    }
    }
  • Strict Class Initialization

    屬性要在建構子直接給值或有初始值

    class C {
    foo: number;
    bar = "hello";
    baz: boolean;
    // ~~~
    // Error! Property 'baz' has no initializer and is not definitely assigned in the
    // constructor.
    constructor() {
    this.foo = 42;
    }
    }

    因為在 _initialize() 會間接給 foo 值,所以在 foo 屬性加上 ! (definite assignment assertion)

    class C {
    foo!: number;
    // ^
    // Notice this '!' modifier.
    // This is the "definite assignment assertion"
    constructor() {
    this._initialize(); // 間接初始化
    }

    private _initialize() {
    this.foo = 0;
    }
    }

    Ref: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html